﻿using System.Globalization;
using blackhouse.BlackApart.Business;
using blackhouse.BlackApart.Business.Apartments;
using blackhouse.BlackApart.Business.Opinions;
using blackhouse.BlackApart.Business.Prices;
using blackhouse.BlackApart.Business.Reservations;
using blackhouse.BlackApart.Web;
using blackhouse.StareKino.Web.ApartmentType;
using System;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using blackhouse.Web;

namespace blackhouse.StareKino.Web.Modules {
    public partial class ApartmentDetailsModule : UserControl {

        #region Fields

        private IApartmentGroup group;
        private IApartmentPrice price;
        private StatisticsOpinion opinions;
        private Factory factory = Factory.Instance();
        private SearchState queryState = SearchState.GetFromContext();
        private AdditionalInformationApartmentType additionalInformation;
        private string opinionPageUrl = String.Empty;

        #endregion

        #region Methods

        private void SetInstance(IApartmentGroup tableGroup, Variant variant) {
            this.group = tableGroup;
            if (variant != null)
                this.price = variant.Price;
            else
                this.price = this.factory.GetApartmentGroupPrice(tableGroup);
            this.opinions = Factory.Instance().GetStatisticsOpinion();
            this.opinions.SetFilterByApartmentType(tableGroup.Id);
            this.additionalInformation = new AdditionalInformationApartmentType(this.group);
            this.opinionPageUrl = this.GetOpinionsUrl();
            if (!String.IsNullOrEmpty(this.opinionPageUrl))
                this.opinionPageUrl = this.opinionPageUrl + "?apartments=" + this.group.Id;
        }

        private string GetOpinionsUrl() {
            var opinionsPage = new mojoPortalExtend.PageProvider().FindCmsPageByFunctionality("opinions");
            return (opinions != null) ? mojoPortalExtend.PageProvider.AdjustUrlToCurrentSite(opinionsPage.Url) : String.Empty;
        }

        public void PopulateControl(IApartmentGroup tableGroup, Variant variant) {
            this.SetInstance(tableGroup, variant);

            if (variant != null)
                this.PopulateRoomsCount(variant.ApartmentCount);

            this.ltlOpinion.Text = this.opinions.GetAverageRatingAsText();
            this.ltlOpinionText.Text = this.opinions.GetAverageRatingText();

            this.ltlOpinionsCount.Text = this.opinions.BasedOnNumberOfOpinions().ToString(CultureInfo.InvariantCulture);
            if (!String.IsNullOrEmpty(this.opinionPageUrl))
                this.ltlLinkToOpinions.Text = this.opinionPageUrl;

            var globalResourceObject = GetGlobalResourceObject("Apartments", "mPersons");
            if (globalResourceObject != null)
                this.ltlMaxPeoples.FormatOnTextFormat(this.@group.NumberOfPeople, globalResourceObject.ToString());

            if (variant != null) {
                this.lblPriceSet.Visible = true;
                this.lblPricePersonNight.Value = this.price.GetPricePerNight();
            } else {
                this.lblPriceNoSet.Visible = true;
                this.lblPricePersonNight.Precision = 0;
                this.lblPricePersonNight.Value = this.price.GetPromoPriceFrom(tableGroup);
            }

            if (variant != null) {
                this.phPriceAll.Visible = true;
                if (variant.Price.GetRabatValue() < 0) {
                    this.lblPriceAllTotal.Visible = false;
                    this.lblNewPriceAll.Visible = true;
                    this.phOldPrice.Visible = true;
                    this.lblPrevPriceAll.Value = this.price.GetPriceWithoutRabat();
                    this.phPricePerNight.Visible = false;
                    this.phDiscount.Visible = true;
                    this.ltlDiscountValue.Text = string.Format("{0}%", variant.Price.GetRabatValue());
                    this.ltlDiscountName.Text = String.Join("<br />", variant.Price.GetAssociacedRabats().Select(r => r.RabatName).ToArray());
                }
                this.lblPriceAll.Value = this.price.GetPrice();

                this.phAllNights.Visible = true;
                int nights = (int)(this.queryState.DepartureDate.Date - this.queryState.ArrivalDate.Date).TotalDays;
                string nightText = nights + " ";
                if (nights == 1)
                    nightText += GetGlobalResourceObject("Reservation", "nights1");
                if (nights > 1 && nights <= 4)
                    nightText += GetGlobalResourceObject("Reservation", "nights24");
                if (nights > 4)
                    nightText += GetGlobalResourceObject("Reservation", "nightsmore");
                this.lblNight.Text = nightText;

                this.phAllPersons.Visible = true;

                this.lblPersons.Text = GetVariantPersonsText(variant);
            }

            this.ltlSurface.Text = this.group.AreaSize.ToString("F0");

            this.rptFields.DataSource = this.group.Fields.OrderBy(f => f.Title).Take(2);
            this.rptFields.DataBind();

            if (this.queryState.IsSet && variant == null)
                this.phNoFreeInfo.Visible = true;

            if (this.additionalInformation.Floor == 0)
            {
                var resourceObject = GetGlobalResourceObject("Apartments", "botFloor");
                if (resourceObject != null)
                    this.ltlFloor.Text = resourceObject.ToString();
            }
            else
                this.ltlFloor.Text = this.additionalInformation.Floor.ToRoman() + @" " + GetGlobalResourceObject("Apartments", "floor");
        }

        private string GetVariantPersonsText(Variant variant) {
            bool extraBed = (variant.Price is PriceWithAdditionalServices
                             && (variant.Price as PriceWithAdditionalServices).HaveService("extrabed"));
            int persons = variant.Price.ReservationNumberOfPeoples;
            if (extraBed)
                persons--;
            string personsText = persons + " ";
            if (persons == 1)
                personsText += GetGlobalResourceObject("Reservation", "personOne");
            if (persons > 1 && persons <= 4)
                personsText += GetGlobalResourceObject("Reservation", "personMoreOne");
            if (persons > 4)
                personsText += GetGlobalResourceObject("Reservation", "personMany");
            if (extraBed)
                personsText += GetGlobalResourceObject("Apartments", "extraBed");
            return personsText;
        }

        private void PopulateRoomsCount(int count) {
            this.phMoreOne.Visible = count > 1;
            this.ltlApartmentsCount.Text = count.ToString(CultureInfo.InvariantCulture);
        }

        protected void rptFields_ItemDataBound(object sender, RepeaterItemEventArgs e) {
            switch (e.Item.ItemType) {
                case ListItemType.AlternatingItem:
                case ListItemType.Item:

                    Panel pnlField = e.Item.FindControl("pnlField") as Panel;
                    Literal ltlTitle = e.Item.FindControl("ltlTitle") as Literal;
                    Literal ltlValue = e.Item.FindControl("ltlValue") as Literal;

                    ApartmentOptionField field = e.Item.DataItem as ApartmentOptionField;

                    if (field != null) {
                        if (pnlField != null && !string.IsNullOrEmpty(field.Description))
                            pnlField.Attributes.Add("toolpop", field.Description);
                        if (ltlTitle != null)
                            ltlTitle.Text = field.Title;
                        if (ltlValue != null)
                            ltlValue.Text = field.Variant.OptionFieldToString();
                    }

                    break;

            }

        }

        #endregion

    }
}